import {
    app,
    protocol,
    BrowserWindow,
    Menu,
    ipcMain,
    Tray,
    nativeImage,
    shell,
    desktopCapturer,
    screen,
    dialog
} from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'
import path from 'path'
import fs from 'fs'
import Store from 'electron-store'
Store.initRenderer()

protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])

// 设置大小
ipcMain.on('setSize', (event, width, height) => {
    mainWindow.setContentSize(width, height)
    event.returnValue = 'pong' //对应渲染进程中的同步方法
})

// 闪烁
ipcMain.on('flash', (event, number) => {
    if (process.platform !== 'darwin') {
        if (!mainWindow.isVisible() || mainWindow.isMinimizable()) {
            // 闪烁托盘
            clearFlashIconTimer()
            let count = 0
            flashIconTimer = setInterval(function () {
                count++
                if (count % 2 === 0) {
                    appIcon.setImage(nativeImage.createEmpty())
                } else {
                    appIcon.setImage(nativeImage.createFromPath(path.join(__static + '/nh', iconPath)))
                }
            }, 500)
            // 闪烁任务栏
            mainWindow.flashFrame(true)
        }
    } else {
        app.dock.setBadge(number === 0 ? '' : number + '')
    }
    event.returnValue = 'pong' //对应渲染进程中的同步方法
})

// 帮助
ipcMain.on('opennew', (event, data) => {
    let smWin = new BrowserWindow({
        center: true,
        width: 400,
        height: 400,
        resizable: false,
        maximizable: false,
        autoHideMenuBar: true,
        useContentSize: true,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        smWin.loadURL(
            process.env.WEBPACK_DEV_SERVER_URL + '#/' + data + '?platform=' + process.platform + '&arch=' + process.arch
        )
    } else {
        smWin.loadURL('app://./index.html#/' + data + '?platform=' + process.platform + '&arch=' + process.arch)
    }
    event.returnValue = 'pong' //对应渲染进程中的同步方法
})

// 单下载可选择路径
ipcMain.on('download', (event, url, fileName) => {
    if (fileName) {
        dialog
            .showSaveDialog(mainWindow, {
                title: '另存为',
                defaultPath: fileName
            })
            .then(result => {
                let filePath = result.filePath
                if (filePath) {
                    mainWindow.webContents.downloadURL(url)
                    mainWindow.webContents.session.once('will-download', (event, item, webContents) => {
                        if (!filePath) return
                        //设置下载项的保存文件路径
                        item.setSavePath(filePath)
                    })
                }
            })
    } else {
        mainWindow.webContents.downloadURL(url)
    }
    event.returnValue = 'pong' //对应渲染进程中的同步方法
})

// 下载后直接打开
ipcMain.on('openPath', (event, url, fileName) => {
    let sourcePath = path.join(
        app.getAppPath().replace('app.asar', ''),
        '/download',
        url.substring(url.lastIndexOf('/') + 1)
    )
    let destPath = path.join(app.getAppPath().replace('app.asar', ''), '/download', `${fileName}`)
    let isExist = fs.existsSync(sourcePath)
    if (isExist) {
        fs.copyFileSync(sourcePath, destPath)
        shell.openPath(destPath)
    } else {
        mainWindow.webContents.downloadURL(url)
        mainWindow.webContents.session.once('will-download', (event, item, webContents) => {
            //设置保存路径
            item.setSavePath(sourcePath)
            item.once('done', (event, state) => {
                if (state === 'completed') {
                    fs.copyFileSync(sourcePath, destPath)
                    shell.openPath(destPath)
                }
            })
        })
    }
    event.returnValue = 'pong'
})

ipcMain.on('screenshot', (event, args) => {
    createCaptureWindow()
    if (args.hidden) {
        mainWindow.minimize()
    }
    event.returnValue = 'pong'
})

ipcMain.handle('capture', async event => {
    let capturer = {
        width: size.width,
        height: size.height,
        sources: await desktopCapturer.getSources({ types: ['window', 'screen'] })
    }
    return capturer
})

ipcMain.on('close', (event, args) => {
    mainWindow.show()
    if (args.type === 'success') {
        mainWindow.webContents.send('capture-screen', args.data)
    }
    captureWindow.close()
    event.returnValue = 'pong'
})

ipcMain.handle('getScreenStream', async event => {
    let sources = await desktopCapturer.getSources({ types: ['screen'] })
    return sources
})

ipcMain.handle('getSize', event => {
    const { size } = screen.getPrimaryDisplay()
    return { width: size.width, height: size.height }
})

//刷新托盘定时器
let flashIconTimer = null
let mainWindow = null
let captureWindow = null
let remoteWindow = null
let floatWindow = null

async function createMainWindow() {
    // 禁止程序多开
    if (!app.requestSingleInstanceLock()) {
        app.quit()
        return
    }

    mainWindow = new BrowserWindow({
        center: true,
        width: 953,
        height: 660,
        resizable: false,
        maximizable: false,
        autoHideMenuBar: true,
        useContentSize: true,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
    } else {
        createProtocol('app')
        mainWindow.loadURL('app://./index.html')
    }

    // 隐藏任务栏
    mainWindow.on('close', event => {
        if (process.platform !== 'darwin') {
            mainWindow.hide() // 隐藏主程序窗口
            mainWindow.setSkipTaskbar(true) // 取消任务栏显示
            event.preventDefault() // 阻止退出程序
        } else {
            mainWindow.hide()
            event.preventDefault()
        }
    })

    let iconPath = '16x16.png'

    const appIcon = createTray(iconPath)

    // 点击任务栏
    mainWindow.on('focus', () => {
        if (process.platform !== 'darwin') {
            clearFlashIconTimer()
            appIcon.setImage(nativeImage.createFromPath(path.join(__static + '/nh', iconPath)))
            mainWindow.flashFrame(false)
        } else {
            app.dock.setBadge('')
        }
    })
}

async function createCaptureWindow() {
    const { size } = screen.getPrimaryDisplay()
    let width = size.width
    let height = size.height
    captureWindow = new BrowserWindow({
        width,
        height,
        autoHideMenuBar: true,
        useContentSize: true,
        movable: false,
        frame: false,
        resizable: false,
        hasShadow: false,
        transparent: true,
        fullscreenable: true,
        fullscreen: true,
        simpleFullscreen: true,
        alwaysOnTop: false,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            preload: path.join(__dirname, 'preload.js')
        }
    })
    captureWindow.setAlwaysOnTop(true, 'screen-saver') // mac
    captureWindow.setVisibleOnAllWorkspaces(true) // mac
    captureWindow.setFullScreenable(true) // mac
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await captureWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL + '#/capture')
    } else {
        captureWindow.loadURL('app://./index.html#/capture')
    }
}

/**
 * 创建托盘图标
 *
 * @param iconPath
 */
function createTray(iconPath) {
    // 托盘
    const appIcon = new Tray(nativeImage.createFromPath(path.join(__static + '/nh', iconPath)))
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '退出',
            click: () => {
                app.exit()
            }
        }
    ])
    appIcon.setToolTip('政务通')
    appIcon.setContextMenu(contextMenu)
    appIcon.on('click', function () {
        showMain(appIcon, iconPath)
    })

    return appIcon
}

/**
 * 展示窗口，打开任务栏
 */
function showMain(appIcon, iconPath) {
    mainWindow.setSkipTaskbar(false)
    mainWindow.show()
    clearFlashIconTimer()
    appIcon.setImage(nativeImage.createFromPath(path.join(__static + '/nh', iconPath)))
}

/**
 * 清除图片闪烁的定时器
 */
function clearFlashIconTimer() {
    if (flashIconTimer) {
        clearInterval(flashIconTimer)
    }
}

// 当运行第二个实例时，将会聚焦到win这个窗口
app.on('second-instance', () => {
    if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        if (mainWindow.isVisible()) {
            mainWindow.focus()
        } else {
            mainWindow.show()
            mainWindow.setSkipTaskbar(false)
        }
    }
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createMainWindow()
    } else {
        mainWindow.show()
    }
})

app.on('ready', async () => {
    await createMainWindow()
})

if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', data => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
